package mars.io.formatters

import java.io.File
import javax.xml.XMLConstants
import javax.xml.transform.stream.StreamSource
import javax.xml.validation.Schema
import javax.xml.validation.SchemaFactory
import javax.xml.validation.Validator
import org.xml.sax.SAXException
import java.net.URL
import java.io.StringBufferInputStream

object XMLValidator {

    /**
     * Checks wether the given xml content is valid according to the given xml schema
     *
     * @param 	xmlContent
     * 			The xml content to check
     * @param	xsdFile
     * 			The location of the xml schema
     */
    def isValid(xmlContent: String, xsdFile: URL): Boolean = {
        try {
            val factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
            val schema = factory.newSchema(xsdFile)
            val validator = schema.newValidator()
            validator.validate(new StreamSource(new StringBufferInputStream(xmlContent)))
        }
        catch {
            case ex: SAXException =>
                println(ex.getMessage())
                return false
            case ex: Exception =>
                println("Error validating occured when the xml")
                throw ex
        }
        return true
    }
}